/*
 * @Descripttion: 核酸宝项目前端
 * @version: 
 * @Author: 杜宇轩
 * @Date: 2022-05-22 05:23:33
 * @LastEditors: 杜宇轩
 * @LastEditTime: 2022-05-22 06:19:01
 */
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '@/pages/Home.vue';
import Login from '@/pages/Login.vue';
import Register from '@/pages/Register.vue';

// 导入所有路由
const allComponents = require.context('./modules/', false, /^.*\.js$/);
const res_components = [];
allComponents.keys().forEach(fileName => {
  if (fileName !== './index.js') {
    const comp = allComponents(fileName);
    res_components.push(...comp.default);
  }
});

Vue.use(VueRouter);

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/',
    component: Home,
    children: [
        ...res_components,
      {
        path: '/',
        redirect: { name: 'Home' }
      }
    ]
  },
  {
    path: '*',
    redirect: { name: 'Home' }
  }
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => { // 路由守卫
  if (to.path === '/login' || to.path === '/register') return next(); // 登录和注册不需要检测直接返回
  const check = localStorage.getItem('NATMS_commonUser');
  if (!check) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    });
  }
  const userInfo = JSON.parse(check);
  const token = userInfo.token;
  if (!token || token === {} || !token.token || !token.lastTime ||
      !userInfo.userId || !userInfo.username || !userInfo.type || userInfo.type === '') {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    });
  }
  const nowTime = new Date().getTime(); // 当前时间
  const lastTime = token.lastTime; // 获取上次时间
  const expirationTime = 1 * 24 * 60 * 60 * 1000; // 过期时间 天数 * 小时 * 分钟 * 秒 * 毫秒
  if (nowTime - lastTime > expirationTime) { // token过期了，进行重定向
    localStorage.removeItem('NATMS_commonUser');
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    });
  }
  next();
});

export default router;
